﻿using DotNetCore.CAP.Messages;
using DotNetCore.CAP.Transport;
using Microsoft.Extensions.Logging;

namespace CapHttp.Core;

public class HttpConsumerClient : IConsumerClient
{
    private readonly HttpConsumerMiddleware _httpConsumerMiddleware;
    private readonly string _groupName;
    private readonly ILogger<HttpConsumerClient> _logger;
    
    public HttpConsumerClient(HttpConsumerMiddleware httpConsumerMiddleware, string groupName, ILogger<HttpConsumerClient> logger)
    {
        _httpConsumerMiddleware = httpConsumerMiddleware;
        _groupName = groupName;
        _logger = logger;

        httpConsumerMiddleware.RegisterConsumerClient(this, groupName);
    }
    
    public void Dispose()
    {
        _httpConsumerMiddleware.Unsubscribe(_groupName);
    }

    public void Subscribe(IEnumerable<string> topics)
    {
        if (topics == null) throw new ArgumentNullException(nameof(topics));
        
        _httpConsumerMiddleware.Subscribe(_groupName, topics);
    }

    public void Listening(TimeSpan timeout, CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            cancellationToken.WaitHandle.WaitOne(timeout);
        }
    }

    public void Commit(object sender)
    {
        
    }

    public void Reject(object sender)
    {
        
    }

    public BrokerAddress BrokerAddress => new BrokerAddress("Http");
    public event EventHandler<TransportMessage>? OnMessageReceived;
    public event EventHandler<LogMessageEventArgs>? OnLog;

    internal void OnMessage(TransportMessage message)
    {
        OnMessageReceived?.Invoke(null, message);
    }
}